package admin

import (
	"time"

	"github.com/labstack/echo/v4"
	"techoiceness.com/aiagent/llm-gateway/internal/entity"
	"techoiceness.com/aiagent/llm-gateway/internal/server/response"
)

// GetDashboardStats 获取仪表盘统计数据
func (h *AdminHandler) GetDashboardStats(c echo.Context) error {
	// 获取基本统计
	var userCount, conversationCount, messageCount, systemPromptCount int64

	// 并行查询基本计数
	h.db.Model(&entity.User{}).Count(&userCount)
	h.db.Model(&entity.Conversation{}).Count(&conversationCount)
	h.db.Model(&entity.ClientMessage{}).Count(&messageCount)
	h.db.Model(&entity.SystemPrompt{}).Count(&systemPromptCount)

	// 获取今日时间范围
	now := time.Now()
	todayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
	todayEnd := todayStart.Add(24 * time.Hour)

	// 获取本月时间范围
	monthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
	nextMonth := monthStart.AddDate(0, 1, 0)

	// 获取最近一小时时间范围
	oneHourAgo := now.Add(-1 * time.Hour)

	// Token使用统计
	var tokenUsage DashboardTokenUsage

	// 今日Token使用量
	h.db.Model(&entity.ClientMessage{}).
		Where("role = ? AND created_at >= ? AND created_at < ? AND tokens_used > 0", "assistant", todayStart, todayEnd).
		Select("COALESCE(SUM(tokens_used), 0)").
		Scan(&tokenUsage.TotalTokensToday)

	// 本月Token使用量
	h.db.Model(&entity.ClientMessage{}).
		Where("role = ? AND created_at >= ? AND created_at < ? AND tokens_used > 0", "assistant", monthStart, nextMonth).
		Select("COALESCE(SUM(tokens_used), 0)").
		Scan(&tokenUsage.TotalTokensThisMonth)

	// 平均每条消息Token数
	var totalTokens int64
	var totalMessages int64
	h.db.Model(&entity.ClientMessage{}).
		Where("role = ? AND tokens_used > 0", "assistant").
		Select("COALESCE(SUM(tokens_used), 0)").
		Scan(&totalTokens)
	h.db.Model(&entity.ClientMessage{}).
		Where("role = ? AND tokens_used > 0", "assistant").
		Count(&totalMessages)

	if totalMessages > 0 {
		tokenUsage.AvgTokensPerMessage = float64(totalTokens) / float64(totalMessages)
	}

	// 近期活动统计
	var activity DashboardActivity

	// 今日新用户
	h.db.Model(&entity.User{}).
		Where("created_at >= ? AND created_at < ?", todayStart, todayEnd).
		Count(&activity.NewUsersToday)

	// 今日新对话
	h.db.Model(&entity.Conversation{}).
		Where("created_at >= ? AND created_at < ?", todayStart, todayEnd).
		Count(&activity.NewConversationsToday)

	// 最近一小时消息数
	h.db.Model(&entity.ClientMessage{}).
		Where("created_at >= ?", oneHourAgo).
		Count(&activity.MessagesLastHour)

	// 今日活跃用户（发送过消息的用户）
	h.db.Model(&entity.ClientMessage{}).
		Where("created_at >= ? AND created_at < ?", todayStart, todayEnd).
		Distinct("user_id").
		Count(&activity.ActiveUsersToday)

	responseData := GetDashboardStatsResponse{
		UserCount:         userCount,
		ConversationCount: conversationCount,
		MessageCount:      messageCount,
		SystemPromptCount: systemPromptCount,
		TokenUsage:        tokenUsage,
		RecentActivity:    activity,
	}

	return response.Success(c, responseData)
}
